<?php
// 命名空间定义
namespace app\index\controller;
 
use app\common\controller\IndexController;
use think\App;


class Index extends IndexController
{
    /**
     * 初始化方法
     */
    protected function initialize()
    {
        parent::initialize();
    }
    public function index(){
        return $this->fetch();
    }
    public function callback(){
        // return; 
        $param = $this->request->param();
        if(count(explode('_',$param['state'])) > 1){
            header("Location: http://192.168.2.31:8080/h5/?code={$param['code']}&state={$param['state']}#/pages/Totalofproducts/Totalofproducts");
        }else{
            header("Location: http://192.168.2.31:8080/h5/?code={$param['code']}&state={$param['state']}#/pages/login/login");
        }
        // if(count(explode('_',$param['state'])) > 1){
        //     header("Location: https://hosj4bb2pabe-5768.beijing-02.dayunet.com/?code={$param['code']}&state={$param['state']}#/pages/Totalofproducts/Totalofproducts");
        // }else{
        //     header("Location: https://hosj4bb2pabe-5768.beijing-02.dayunet.com/?code={$param['code']}&state={$param['state']}#/pages/login/login");
        // }
    }
//    订阅物流
    public function kuaidiPoll($data){
        // 参数设置
        $key = config('app.kuaidi.key');                            // 客户授权key
        $param = array (
            'company' => '',             // 快递公司编码
            'number' => $data['number'],      // 快递单号
            // 'from' => '',                     // 出发地城市
            // 'to' => '',                       // 目的地城市
            'key' => $key,                    // 客户授权key
            'parameters' => array (
                'callbackurl' => $this->request->domain(true).'/api/index/kuaidiCallback',          // 回调地址
                // 'salt' => '',                 // 加密串
                'resultv2' => '4',            // 行政区域解析
                'autoCom' => '1',             // 单号智能识别
                // 'interCom' => '0',            // 开启国际版
                // 'departureCountry' => '',     // 出发国
                // 'departureCom' => '',         // 出发国快递公司编码
                // 'destinationCountry' => '',   // 目的国
                // 'destinationCom' => '',       // 目的国快递公司编码
                // 'phone' => ''                 // 手机号
            )
        );
// 请求参数
        $post_data = array();
        $post_data["schema"] = 'json';
        $post_data["param"] = json_encode($param);

        $url = 'http://poll.kuaidi100.com/poll';    //订阅请求地址

        $params = "";
        foreach ($post_data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";     //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);
        $res = curl($url,$post_data);
        $res = json_decode($res,true);
//        var_dump($res);
//        var_dump($post_data);
//        exit;
//        {
//            "result": true,
//    "returnCode": "200",
//    "message": "提交成功"
//}
        if($res['returnCode'] == '200'){
            return true;
        }
        return $res;
    }
    /**
     * 快递回调
     * @return object
     */
    private function kuaidiCallback($post, $type)
    {
//        $statusData = [
//            [
//                'status' => 1,
//                'content' => '揽收',
//                'data' => [
//                    ['status' => 1, 'content' => '揽收', 'details' => '快件揽件'],
//                    ['status' => 101, 'content' => '已下单', 'details' => '已经下快件单'],
//                    ['status' => 102, 'content' => '待揽收', 'details' => '待快递公司揽收'],
//                    ['status' => 103, 'content' => '已揽收', 'details' => '快递公司已经揽收']
//                ]
//            ],
//            [
//                'status' => 0,
//                'content' => '在途',
//                'data' => [
//                    ['status' => 0, 'content' => '在途', 'details' => '快件在途中'],
//                    ['status' => 1001, 'content' => '到达派件城市', 'details' => '快件到达收件人城市'],
//                    ['status' => 1002, 'content' => '干线', 'details' => '快件处于运输过程中'],
//                    ['status' => 1003, 'content' => '转递', 'details' => '快件发往到新的收件地址']
//                ]
//            ],
//            [
//                'status' => 5,
//                'content' => '派件',
//                'data' => [
//                    ['status' => 5, 'content' => '派件', 'details' => '快件正在派件'],
//                    ['status' => 501, 'content' => '投柜或驿站', 'details' => '快件已经投递到快递柜或者快递驿站']
//                ]
//            ],
//            [
//                'status' => 3,
//                'content' => '签收',
//                'data' => [
//                    ['status' => 3, 'content' => '签收', 'details' => '快件已签收'],
//                    ['status' => 301, 'content' => '本人签收', 'details' => '收件人正常签收'],
//                    ['status' => 302, 'content' => '派件异常后签收', 'details' => '快件显示派件异常，但后续正常签收'],
//                    ['status' => 303, 'content' => '代签', 'details' => '快件已被代签'],
//                    ['status' => 304, 'content' => '投柜或站签收', 'details' => '快件已从快递柜或者驿站取出签收']
//                ]
//            ],
//            [
//                'status' => 6,
//                'content' => '退回',
//                'data' => [
//                    ['status' => 6, 'content' => '退回', 'details' => '快件正处于返回发货人的途中']
//                ]
//            ],
//            [
//                'status' => 4,
//                'content' => '退签',
//                'data' => [
//                    ['status' => 4, 'content' => '退签', 'details' => '此快件单已退签'],
//                    ['status' => 401, 'content' => '已销单', 'details' => '此快件单已撤销'],
//                    ['status' => 14, 'content' => '拒签', 'details' => '收件人拒签快件']
//                ]
//            ],
//            [
//                'status' => 7,
//                'content' => '转投',
//                'data' => [
//                    ['status' => 7, 'content' => '转投', 'details' => '快件转给其他快递公司邮寄']
//                ]
//            ],
//            [
//                'status' => 2,
//                'content' => '疑难',
//                'data' => [
//                    ['status' => 2, 'content' => '疑难', 'details' => '快件存在疑难'],
//                    ['status' => 201, 'content' => '超时未签收', 'details' => '快件长时间派件后未签收'],
//                    ['status' => 202, 'content' => '超时未更新', 'details' => '快件长时间没有派件或签收'],
//                    ['status' => 203, 'content' => '拒收', 'details' => '收件人发起拒收快递，待发货方确认'],
//                    ['status' => 204, 'content' => '派件异常', 'details' => '快件派件时遇到异常情况'],
//                    ['status' => 205, 'content' => '柜或驿站超时未取', 'details' => '快件在快递柜或者驿站长时间未取'],
//                    ['status' => 206, 'content' => '无法联系', 'details' => '无法联系到收件人'],
//                    ['status' => 207, 'content' => '超区', 'details' => '超出快递公司的服务区范围'],
//                    ['status' => 208, 'content' => '滞留', 'details' => '快件滞留在网点，没有派送'],
//                    ['status' => 209, 'content' => '破损', 'details' => '快件破损'],
//                    ['status' => 210, 'content' => '销单', 'details' => '寄件人申请撤销寄件']
//                ]
//            ],
//            [
//                'status' => 8,
//                'content' => '清关',
//                'data' => [
//                    ['status' => 8, 'content' => '清关', 'details' => '快件清关'],
//                    ['status' => 10, 'content' => '待清关', 'details' => '快件等待清关'],
//                    ['status' => 11, 'content' => '清关中', 'details' => '快件正在清关流程中'],
//                    ['status' => 12, 'content' => '已清关', 'details' => '快件已完成清关流程'],
//                    ['status' => 13, 'content' => '清关异常', 'details' => '货物在清关过程中出现异常']
//                ]
//            ],
//            [
//                'status' => 14,
//                'content' => '拒签',
//                'data' => [
//                    ['status' => 14, 'content' => '拒签', 'details' => '收件人拒签快件']
//                ]
//            ]
//        ];

//        $param = "{&quot;status&quot;:&quot;polling&quot;,&quot;message&quot;:&quot;&quot;,&quot;lastResult&quot;:{&quot;message&quot;:&quot;ok&quot;,&quot;nu&quot;:&quot;9735767393063&quot;,&quot;ischeck&quot;:&quot;0&quot;,&quot;com&quot;:&quot;zhongtong&quot;,&quot;status&quot;:&quot;200&quot;,&quot;state&quot;:&quot;1&quot;,&quot;data&quot;:[{&quot;time&quot;:&quot;2023-02-02 09:57:03&quot;,&quot;context&quot;:&quot;【长沙市】 【长沙东站】（07**-55**234） 的 长沙东站司法分部（135****1234） 已接单&quot;,&quot;ftime&quot;:&quot;2023-02-02 09:57:03&quot;,&quot;areaCode&quot;:null,&quot;areaName&quot;:null,&quot;status&quot;:null,&quot;location&quot;:null,&quot;areaCenter&quot;:null,&quot;areaPinYin&quot;:null,&quot;statusCode&quot;:null}],&quot;loop&quot;:false}}";
//        array(3) {
//        ["status"]=>
//  string(7) "polling"
//        ["message"]=>
//  string(0) ""
//        ["lastResult"]=>
//  array(8) {
//            ["message"]=>
//    string(2) "ok"
//            ["nu"]=>
//    string(13) "9735767393063"
//            ["ischeck"]=>
//    string(1) "0"
//            ["com"]=>
//    string(9) "zhongtong"
//            ["status"]=>
//    string(3) "200"
//            ["state"]=>
//    string(1) "1"
//            ["data"]=>
//    array(1) {
//                [0]=>
//      array(10) {
//                    ["time"]=>
//        string(19) "2023-02-02 09:57:03"
//                    ["context"]=>
//        string(108) "【长沙市】 【长沙东站】（07**-55**234） 的 长沙东站司法分部（135****1234） 已接单"
//                    ["ftime"]=>
//        string(19) "2023-02-02 09:57:03"
//                    ["areaCode"]=>
//        string(14) "CN430100000000"
//                    ["areaName"]=>
//        string(16) "湖南,长沙市"
//                    ["status"]=>
//        string(6) "揽收"
//                    ["location"]=>
//        string(32) "湖南省 长沙市 长沙东站"
//                    ["areaCenter"]=>
//        string(20) "112.938814,28.228209"
//                    ["areaPinYin"]=>
//        string(13) "chang sha shi"
//                    ["statusCode"]=>
//        string(3) "101"
//      }
//    }
//    ["loop"]=>
//    bool(false)
//  }
//}
        $statusData = [
            1 => 1,
            101 => 1,
            102 => 1,
            103 => 1,
            0 => 0,
            1001 => 0,
            1002 => 0,
            1003 => 0,
            5 => 5,
            501 => 5,
            3 => 3,
            301 => 3,
            302 => 3,
            303 => 3,
            304 => 3,
            6 => 6,
            4 => 4,
            7 => 7,
            2 => 2,
            201 => 2,
            202 => 2,
            203 => 2,
            204 => 2,
            205 => 2,
            206 => 2,
            207 => 2,
            208 => 2,
            209 => 2,
            210 => 2,
            8 => 8,
            10 => 8,
            11 => 8,
            12 => 8,
            13 => 8,
            14 => 14
        ];
        $statusTitleData=[0=>'运输中',1=>'已揽收',2=>'疑件',3=>'已签收',4=>'已退签',5=>'派件中',6=>'已退回',7=>'转投',8=>'清关',14=>'已拒签'];
        $param = json_decode(htmlspecialchars_decode($post['param']),true);
        $data = [];
        $orderLogisticsModel = new OrderLogistics();
        $orderStatus = 0;
        if($param['lastResult']){
            $logistics =  $orderLogisticsModel->where(['nu'=>$param['lastResult']['nu'],'type'=>0])->select()->toArray();
            $logistics = array_reverse($logistics);
            $timeArr  = array_column($logistics,'time');
            $time = array_combine($timeArr,$timeArr);
            foreach($param['lastResult']['data'] as $v){
                $tempData = [
                    'nu' => $param['lastResult']['nu'],
                    'state'=> $statusData[$v['statusCode']],
                    'time'=> strtotime($v['time']),
                    'context' => $v['context'],
                    'ftime' => strtotime($v['ftime']),
                    'areaCode' => $v['areaCode'],
                    'areaName' => $v['areaName'],
                    'status' => $v['status'],
                    'statusTitle'=>$statusTitleData[$statusData[$v['statusCode']]],
                    'location' => $v['location'],
                    'areaCenter' => $v['areaCenter'],
                    'areaPinYin' => $v['areaPinYin'],
                    'statusCode' => $v['statusCode'],
                    'order_type' => $type
                ];
                if($statusData[$v['statusCode']] == 3){
                    $orderStatus = 1;//签收 修改订单状态为完成
                }
                if(!$logistics){
                    $data[] = $tempData;
                }else{
                    if(!isset($time[strtotime($v['time'])])){
                        $data[] = $tempData;
                    }
                }
            }
        }
        $data = array_reverse($data);
        $orderLogisticsModel->startTrans();
        try {
            $orderLogisticsModel->saveAll($data);

            $orderLogisticsModel->commit();
        } catch (\Exception $e) {
            $orderLogisticsModel->rollback();
            var_dump($e->getMessage());
        }
        $ret = [
            'result'=>true,
            'returnCode' => '200',
            'message' => '成功'
        ];
        return json_encode($ret);
    }
}